#ifndef PLUGINMANAGER_H
#define PLUGINMANAGER_H

#include <QObject>
#include <QString>
#include <QList>
#include <QPluginLoader>
#include <QMap>

class PluginManager : public QObject
{
    Q_OBJECT

public:
    explicit PluginManager(QObject *parent = nullptr);
    ~PluginManager();
    
    void loadPlugins();
    void unloadPlugins();
    
    template<typename T>
    QList<T*> getPlugins() const;
    
    QStringList loadedPlugins() const;
    bool isPluginLoaded(const QString &pluginName) const;
    
private:
    struct PluginInfo {
        QPluginLoader *loader;
        QObject *instance;
        QString fileName;
    };
    
    QMap<QString, PluginInfo> m_plugins;
    QString m_pluginsPath;
};

// 模板函数的实现必须放在头文件中
template<typename T>
QList<T*> PluginManager::getPlugins() const
{
    QList<T*> result;
    for (auto it = m_plugins.constBegin(); it != m_plugins.constEnd(); ++it) {
        T *plugin = qobject_cast<T*>(it.value().instance);
        if (plugin) {
            result.append(plugin);
        }
    }
    return result;
}

#endif // PLUGINMANAGER_H